@page "/admin/login"

@using Microsoft.AspNetCore.Components.Authorization
@using MyBlogServer.Services
@using Microsoft.AspNetCore.Authentication
@using System.Security.Claims
@inject UserService UserService
@inject NavigationManager Navigation
@inject CustomAuthenticationStateProvider AuthStateProvider
@inject IHttpContextAccessor HttpContextAccessor
@inject IJwtAuthService JwtAuthService

@rendermode InteractiveServer

<PageTitle>Admin - Login</PageTitle>

<div class="admin-login-container">
    <div class="card">
        <div class="card-header">
            <h3 class="card-title mb-0">管理员登录</h3>
        </div>
        <div class="card-body">
            @if (!string.IsNullOrEmpty(_errorMessage))
            {
                <div class="alert alert-danger">@_errorMessage</div>
            }
            
            <EditForm Model="@loginModel" FormName="loginForm" OnValidSubmit="HandleValidSubmit" OnInvalidSubmit="HandleInvalidSubmit">
                <DataAnnotationsValidator />
                <ValidationSummary />
                
                <div class="mb-3">
                    <label for="username" class="form-label">用户名</label>
                    <InputText id="username" class="form-control" @bind-Value="loginModel.Username" />
                    <div class="form-text">当前输入的用户名: @loginModel.Username</div>
                </div>
                
                <div class="mb-3">
                    <label for="password" class="form-label">密码</label>
                    <InputText id="password" type="password" class="form-control" @bind-Value="loginModel.Password" />
                </div>
                
                <div class="d-grid gap-2">
                    <button type="submit" class="btn btn-primary">登录</button>
                </div>
            </EditForm>
            
            <div class="mt-3 text-center">
                <p class="mb-0">默认账户: admin/admin</p>
            </div>
        </div>
    </div>
</div>

@code {
    private LoginModel loginModel = new();
    private string _errorMessage = string.Empty;

    public class LoginModel
    {
        private string _username = string.Empty;
        private string _password = string.Empty;
        
        public string Username 
        { 
            get => _username;
            set
            {
                Console.WriteLine($"设置用户名: '{value}' (原值: '{_username}')");
                _username = value;
            }
        }
        
        public string Password 
        { 
            get => _password;
            set
            {
                Console.WriteLine($"设置密码: 长度{value.Length} (原长度: {_password.Length})");
                _password = value;
            }
        }
    }
    
    protected override void OnInitialized()
    {
        Console.WriteLine("Login页面初始化");
        Console.WriteLine($"初始化时loginModel值 - 用户名: '{loginModel.Username}'，密码长度: {loginModel.Password.Length}");
    }
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        Console.WriteLine($"OnAfterRenderAsync调用，firstRender: {firstRender}");
        Console.WriteLine($"渲染时loginModel值 - 用户名: '{loginModel.Username}'，密码长度: {loginModel.Password.Length}");
        
        if (!firstRender )
        {
            // 页面初始化时检查是否已经登录
            try
            {
                var token = await JwtAuthService.GetStoredTokenAsync();
                if (!string.IsNullOrEmpty(token) && await JwtAuthService.IsTokenValidAsync())
                {
                    // 如果已经登录，直接跳转到管理页面
                    Console.WriteLine("用户已登录，重定向到管理页面");
                    var usernameFromToken = await JwtAuthService.GetUsernameFromTokenAsync(token);
                    AuthStateProvider.NotifyUserLoggedIn(usernameFromToken);
                    Navigation.NavigateTo("/admin/posts");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"检查登录状态时发生错误: {ex.Message}");
            }
        }
    }
    
    private async Task HandleValidSubmit(EditContext context)
    {
        Console.WriteLine($"=== HandleValidSubmit 开始 ===");
        var model = (LoginModel)context.Model;
        Console.WriteLine($"从EditContext获取的值，用户名: '{model.Username}'，密码长度: {model.Password.Length}");
        Console.WriteLine($"当前loginModel中的值，用户名: '{loginModel.Username}'，密码长度: {loginModel.Password.Length}");
        
        // 使用从EditContext获取的模型数据
        await ProcessLogin(model.Username, model.Password);
        Console.WriteLine($"=== HandleValidSubmit 结束 ===");
    }
    
    private async Task HandleInvalidSubmit()
    {
        _errorMessage = "请检查输入信息";
        Console.WriteLine($"表单验证失败，用户名: '{loginModel.Username}'");
    }
    
    private async Task ProcessLogin(string username, string password)
    {
        try
        {
            Console.WriteLine($"=== ProcessLogin 开始 ===");
            Console.WriteLine($"尝试登录: '{username}'");
            Console.WriteLine($"登录参数检查: 用户名长度={username.Length}, 密码长度={password.Length}");
            
            Console.WriteLine($"传递参数: 用户名='{username}', 密码长度={password.Length}");
            var user = await UserService.AuthenticateAsync(username, password);
            if (user != null)
            {
                Console.WriteLine("登录成功");
                
                // 生成JWT Token
                var token = await JwtAuthService.GenerateTokenAsync(user.Username);
                
                // 存储Token到浏览器localStorage
                await JwtAuthService.StoreTokenAsync(token);
                
                // 登录成功，通知认证状态提供者
                AuthStateProvider.NotifyUserLoggedIn(user.Username);
                
                // 验证状态是否已正确设置
                var authState = await AuthStateProvider.GetAuthenticationStateAsync();
                Console.WriteLine($"认证状态检查: {authState.User?.Identity?.IsAuthenticated}, 用户: {authState.User?.Identity?.Name}");
                
                // 添加延迟以确保状态同步完成
                await Task.Delay(300);
                
                // 跳转到管理页面
                Navigation.NavigateTo("/admin/posts", forceLoad: true); 
            }
            else
            {
                _errorMessage = "用户名或密码错误";
                Console.WriteLine("用户名或密码错误");
            }
            Console.WriteLine($"=== ProcessLogin 结束 ===");
        }
        catch (Exception ex)
        {
            _errorMessage = $"登录时发生错误: {ex.Message}";
            Console.WriteLine($"登录错误: {ex}");
        }
    }
}